package com.ly.emp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.emp.bean.dto.HubTeamIndexDTO;
import com.ly.emp.bean.entity.HubTeamIndex;
import com.ly.emp.bean.entity.HubTeamIndexType;
import com.ly.emp.constant.EmpErrorConstants;
import com.ly.emp.mapper.HubTeamIndexMapper;
import com.ly.emp.service.IHubTeamIndexService;
import com.ly.emp.service.IHubTeamIndexTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 一线班组-指标库表-impl
 *
 * @author luoyun
 * @Date: 2025-06-20
 */
@Service
@RequiredArgsConstructor
public class HubTeamIndexServiceImpl extends ServiceImpl<HubTeamIndexMapper, HubTeamIndex> implements IHubTeamIndexService {

    private final IHubTeamIndexTypeService typeService;

    @Override
    public R getId(String id) {
        HubTeamIndex entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(HubTeamIndex entity) {
        String orgCode = entity.getOrgCode();
        if(StrUtil.isBlank(orgCode)){
            return R.fail(EmpErrorConstants.NO_TEAM);
        }
        List<HubTeamIndex> list = this.list(
                new LambdaQueryWrapper<HubTeamIndex>()
                        .eq(HubTeamIndex::getOrgCode, orgCode)
                        .eq(StrUtil.isNotBlank(entity.getPeriodCode()),HubTeamIndex::getPeriodCode,entity.getPeriodCode())
                        .eq(StrUtil.isNotBlank(entity.getIndexTypeCode()),HubTeamIndex::getIndexTypeCode,entity.getIndexTypeCode())
                        .like(StrUtil.isNotBlank(entity.getIndexTypeName()),HubTeamIndex::getIndexTypeName,entity.getIndexTypeName())
                        .like(StrUtil.isNotBlank(entity.getIndexName()), HubTeamIndex::getIndexName,entity.getIndexName())
                        .orderByAsc(HubTeamIndex::getDisplayOrder)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(HubTeamIndex entity, Page<HubTeamIndex> page) {
        String orgCode = entity.getOrgCode();
        if(StrUtil.isBlank(orgCode)){
            return R.fail(EmpErrorConstants.NO_TEAM);
        }
        IPage<HubTeamIndex> pageList = this.page(page,
                new LambdaQueryWrapper<HubTeamIndex>()
                        .eq(HubTeamIndex::getOrgCode, orgCode)
                        .eq(StrUtil.isNotBlank(entity.getPeriodCode()),HubTeamIndex::getPeriodCode,entity.getPeriodCode())
                        .eq(StrUtil.isNotBlank(entity.getIndexTypeCode()),HubTeamIndex::getIndexTypeCode,entity.getIndexTypeCode())
                        .like(StrUtil.isNotBlank(entity.getIndexTypeName()),HubTeamIndex::getIndexTypeName,entity.getIndexTypeName())
                        .like(StrUtil.isNotBlank(entity.getIndexName()), HubTeamIndex::getIndexName,entity.getIndexName())
                        .orderByAsc(HubTeamIndex::getDisplayOrder));
        return R.ok(pageList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R add(HubTeamIndex entity) {
        List<HubTeamIndex> list = this.list(
                new LambdaQueryWrapper<HubTeamIndex>()
                        .eq(HubTeamIndex::getOrgCode, entity.getOrgCode())
                        .eq(HubTeamIndex::getPeriodCode, entity.getPeriodCode())
                        .eq(HubTeamIndex::getIndexTypeName, entity.getIndexTypeName())
                        .eq(HubTeamIndex::getIndexName, entity.getIndexName())
        );
        if (CollUtil.isNotEmpty(list)) {
            return R.fail("指标名称已存在！");
        }
        //指标类型新版处理
        HubTeamIndexType indexType = BeanUtil.copyProperties(entity,HubTeamIndexType.class,new String[]{"seqKey"});
        String uidCode = typeService.getAndAdd(indexType);
        entity.setIndexTypeCode(uidCode);
        //设置编码
        entity.setIndexCode(IdUtil.getSnowflakeNextIdStr());
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R edit(HubTeamIndex entity) {
        List<HubTeamIndex> list = this.list(
                new LambdaQueryWrapper<HubTeamIndex>()
                        .eq(HubTeamIndex::getOrgCode, entity.getOrgCode())
                        .eq(HubTeamIndex::getPeriodCode, entity.getPeriodCode())
        );
        HubTeamIndex index = list.stream()
                //排除本身且判断指标名称和指标类型名称
                .filter(n -> !entity.getId().equals(n.getId())
                        && entity.getIndexName().equals(n.getIndexName())
                        && entity.getIndexTypeName().equals(n.getIndexTypeName()))
                .findAny().orElse(null);
        if (index!=null) {
            return R.fail("指标名称已存在！");
        }
        //指标类型新版处理
        HubTeamIndexType indexType = BeanUtil.copyProperties(entity,HubTeamIndexType.class,new String[]{"seqKey"});
        String uidCode = typeService.getAndAdd(indexType);
        entity.setIndexTypeCode(uidCode);
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<HubTeamIndex> dto) {
        List<HubTeamIndex> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public R importHistory(HubTeamIndexDTO dto) {
        String periodCode = dto.getPeriodCode();
        String periodCode1 = dto.getPeriodCode1();
        String orgCode = dto.getOrgCode();
        List<HubTeamIndex> list = this.list(
                new LambdaQueryWrapper<HubTeamIndex>()
                        .eq(HubTeamIndex::getPeriodCode,periodCode1)
                        .eq(HubTeamIndex::getOrgCode,orgCode)
        );
        if(CollUtil.isEmpty(list)){
            return R.ok(true,"当前选择的周期，暂无指标数据，请选择其它周期");
        }
        //判断是否已经添加
        List<HubTeamIndex> saveList = new ArrayList<>();
        list.stream().forEach(n ->{
            //判断是否已经同步过，同步过则不再处理
            n.setId(null);
            n.setPeriodCode(periodCode);
            List<HubTeamIndex> entityByNames = this.getEntityByNames(n);
            if(CollUtil.isEmpty(entityByNames)){
                saveList.add(n);
            }
        });
        boolean flag = this.saveOrUpdateBatch(saveList);
        return flag ? R.ok(true,"数据移入成功") : R.fail("数据已经存在，请勿重复移入");
    }

    /**
     * 根据名字判断是否已经存在
     * @param entity
     * @return
     */
    public List<HubTeamIndex> getEntityByNames(HubTeamIndex entity){
        return this.list(
                new LambdaQueryWrapper<HubTeamIndex>()
                        .eq(HubTeamIndex::getOrgCode,entity.getOrgCode())
                        .eq(HubTeamIndex::getPeriodCode,entity.getPeriodCode())
                        .eq(HubTeamIndex::getIndexName,entity.getIndexName())
                        .eq(HubTeamIndex::getIndexTypeName,entity.getIndexTypeName())
        );
    }
}
